package org.apoiolivre.server;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apoiolivre.model.Movement;

public class BuscaMovimento extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		String where = req.getParameter("desc")!=null?req.getParameter("desc"):"";
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + Movement.class.getName();
		
		if(where.length()>0)
		query = query + " where " + where;
		
		try {
			@SuppressWarnings("unchecked")
			List<Movement> movimentos = (List<Movement>) pm.newQuery(query).execute();
			resp.getWriter().println("[");
			Integer size = movimentos.size();
			Integer count = 1;
			for(Movement mov: movimentos) {
				resp.getWriter().println("{\"key\":\""+mov.getKey().getId()+"\"," +
						"\"date\":\""+mov.getDate().toString()+"\"," +
						"\"value\":\""+mov.getValue().toString()+"\"," +
						"\"quantity\":\""+mov.getQuantity().toString()+"\"," +
						"\"description\":\""+mov.getDescription().toString()+"\"" +
											"}");
				if(!count.equals(size)) resp.getWriter().print(",");
				count++;
			}

			resp.getWriter().println("]");
		} 
		catch (Exception e) {
			resp.getWriter().println("error: "+e.getMessage());
			resp.getWriter().println("-------------------------");
			e.printStackTrace();
		}
		finally {
			pm.close();
		}

	}
}
